﻿#region copyright
//Copyright 2013 Ramon Ordiales Plaza
//
//This file is part of TrayFastMsg.
//
//    TrayFastMsg is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    TrayFastMsg is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with FastMessage.  If not, see <http://www.gnu.org/licenses/>.
//
#endregion
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TrayFastMsg
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public MsgManager MsgManager { get; set; }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void pictureBox1_MouseEnter(object sender, EventArgs e)
        {
            pictureBox1.Image = TrayFastMsg.Properties.Resources.downblanco;
        }

        private void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = TrayFastMsg.Properties.Resources.downblancoleave;
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            pictureBox1.Image = TrayFastMsg.Properties.Resources.downblancoclick;
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            pictureBox1.Image = TrayFastMsg.Properties.Resources.downblanco;
        }

        private void pictureBox2_MouseEnter(object sender, EventArgs e)
        {
            pictureBox2.Image = TrayFastMsg.Properties.Resources.exit_icon16over;
        }

        private void pictureBox2_MouseLeave(object sender, EventArgs e)
        {
            pictureBox2.Image = TrayFastMsg.Properties.Resources.exit_icon16;
        }

        private void pictureBox2_MouseDown(object sender, MouseEventArgs e)
        {
            pictureBox2.Image = TrayFastMsg.Properties.Resources.exit_icon16down;
        }

        private void pictureBox2_MouseUp(object sender, MouseEventArgs e)
        {
            pictureBox2.Image = TrayFastMsg.Properties.Resources.exit_icon16over;
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        public void AjListado(){
            listado.SelectedItem =-1;
            listado.Items.Clear();
            listado.Items.AddRange(MsgManager.msgData.ToArray());
            listado.SelectedIndex=listado.Items.Count-1;
            this.Opacity = 1;
            AjCounter();
        }
        public void OnNewMessage(object sender,EventArgs e){
            AjListado();
        }

        private void AjCounter()
        {
            if (listado.Items.Count == 0)
                label1.Text = "Ningun mensaje";
            else
                label1.Text = string.Format("{0} mensajes", listado.Items.Count);
        }

        private void listado_DrawItem(object sender, DrawItemEventArgs e)
        {
            FastMessage.Message item = null;
            if (e.Index >= 0) item = (FastMessage.Message)(listado.Items[e.Index]);
            
            e.DrawBackground();
            if (item == null) return;
            var g = e.Graphics;
            var fg = new SolidBrush(e.ForeColor);
            var r1 = new Rectangle(e.Bounds.Location, new Size(e.Bounds.Width, 16));
            var r2 = new Rectangle(r1.Left,r1.Bottom,r1.Width,16*2);
            var r2in = new Rectangle(r2.Left + 17, r2.Top + 1, r2.Width - 18, r2.Height - 2);
            var bg2 = new SolidBrush(Color.YellowGreen);
            g.FillRectangle(bg2,r2in);
            var img = (e.ForeColor.GetBrightness() > 0.5) ? Properties.Resources.minitrashblanco : Properties.Resources.minitrashnegro;
            g.DrawImageUnscaled(img,r1.X+1,r1.Y+2);
            var r1a = new Rectangle(r1.X+18,r1.Y,100-18, r1.Height);
            g.DrawString(item.Fecha.ToString("dd/MM/yy hh:mm"), e.Font, fg,r1a);
            r1a = new Rectangle(r1a.Right, r1a.Top, r1.Width - 100, r1.Height);
            g.DrawString(item.Origen, e.Font, fg, r1a);
            g.DrawString(item.Texto, e.Font, fg, r2in);
        }

        private void listado_Click(object sender, EventArgs e)
        {
            
        }

        private void listado_MouseClick(object sender, MouseEventArgs e)
        {
            var p = e.Location;
            if (p.X > 16) return;
            var i=listado.IndexFromPoint(p);
            if (i < 0) return;
            var b = listado.GetItemRectangle(i);
            if ((p.Y - b.Y) > 16) return;

                var item = (FastMessage.Message)listado.Items[i];
                if (i == listado.SelectedIndex) listado.SelectedIndex = -1;
                listado.Items.RemoveAt(i);
                MsgManager.msgData.Remove(item);
                AjCounter();
                if (MsgManager.NoMsg) MsgManager.SetIcon();
        }

        private void pictureBox3_MouseLeave(object sender, EventArgs e)
        {
            pictureBox3.Image = TrayFastMsg.Properties.Resources.gearleave;
        }

        private void pictureBox3_MouseEnter(object sender, EventArgs e)
        {
            pictureBox3.Image = TrayFastMsg.Properties.Resources.gearover;
        }

        private void pictureBox3_MouseDown(object sender, MouseEventArgs e)
        {
            pictureBox3.Image = TrayFastMsg.Properties.Resources.geardown;
        }

        private void pictureBox3_Click(object sender, EventArgs e)
        {
           
        }

        private void pictureBox3_MouseClick(object sender, MouseEventArgs e)
        {
            var p = new Point(pictureBox3.Right - pictureBox3.ContextMenuStrip.Width, pictureBox3.Bottom);
            p = pictureBox3.Parent.PointToScreen(p);
            pictureBox3.ContextMenuStrip.Show(p);
        }

        private void inicioAutomáticoToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
        {
            var newv = inicioAutomáticoToolStripMenuItem.Checked;
            var oldv = CheckInicio();
            if (newv != oldv)
            {
                SetInicio(newv);
            }
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            var b = CheckInicio();
            inicioAutomáticoToolStripMenuItem.Checked = b;
            debugToolStripMenuItem.Checked = CheckDebug();

        }
        private string RegKeyName = "TrayFastMessage";
        private string runpath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
        private bool CheckInicio()
        {
            using (var run = Registry.CurrentUser.OpenSubKey(runpath, false))
            {
                return run.GetValueNames().Contains(RegKeyName, StringComparer.OrdinalIgnoreCase);
            }
        }
        private void SetInicio(bool v)
        {
            using (var run = Registry.CurrentUser.OpenSubKey(runpath, true))
            {
                if (v)
                {
                    run.SetValue(RegKeyName, "\"" + Application.ExecutablePath.ToString() + "\"");
                }
                else
                {
                    run.DeleteValue(RegKeyName);
                }
            }
        }
        private Timer outtimer;
        public void Form1_MouseLeave(object sender, EventArgs e)
        {
            if (outtimer == null)
            {
                outtimer = new Timer();
                outtimer.Interval = 100;
                outtimer.Tick += outtimer_Tick;
            }
            outtimer.Start();
        }

        void outtimer_Tick(object sender, EventArgs e)
        {
            var o = this.Opacity;
            if (o > 0.2)
                this.Opacity -= 0.01;
            else
            {
                this.Close();
                
            }
            
        }

        public void Form1_MouseEnter(object sender, EventArgs e)
        {
            if (outtimer != null) outtimer.Stop();
            this.Opacity = 1;
        }
        private MouseMoveMessageFilter mouseMessageFilter;
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.mouseMessageFilter = new MouseMoveMessageFilter();
            this.mouseMessageFilter.TargetForm = this;
            Application.AddMessageFilter(this.mouseMessageFilter);
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            Application.RemoveMessageFilter(this.mouseMessageFilter);
        }

        class MouseMoveMessageFilter : IMessageFilter
        {
            public Form1 TargetForm { get; set; }
            public bool? Dentro;
            public bool PreFilterMessage(ref Message m)
            {
                int numMsg = m.Msg;
                if (numMsg == 0x0200 /*WM_MOUSEMOVE*/)
                {
                    if (Dentro!=true){
                        Dentro = true;
                        this.TargetForm.Form1_MouseEnter(this,new EventArgs());
                    }
                }
                if (numMsg == 0x02A3 /*WM_MOUSELEAVE*/)
                {
                    Dentro = false;
                    this.TargetForm.Form1_MouseLeave(this, new EventArgs());
                }

                return false;
            }

        }

        private void debugToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
        {
            var newv = debugToolStripMenuItem.Checked;
            var oldv = CheckDebug();
            if (newv != oldv)
            {
                MsgManager.ReadTask.Debugmode = newv;
            }
        }

        private bool CheckDebug()
        {
            return MsgManager.ReadTask.Debugmode;
        }
    }
}
